<template>
  <div class="admin">
    <el-container class="layout-container">
      <!-- 头部 -->
      <el-header class="app-header">
        <div class="header-content">
          <h1 class="header-title">管理后台</h1>
          <p class="header-subtitle">访客信息审核与管理</p>
        </div>
      </el-header>

      <!-- 主体内容 -->
      <el-main class="app-main">
        <div class="main-container">
          <!-- 标签页 -->
          <el-tabs v-model="activeTab" type="border-card" class="admin-tabs">
            <!-- 待审核 -->
            <el-tab-pane label="待审核" name="pending">
              <div class="tab-header">
                <h3>待审核访客列表</h3>
                <el-badge :value="pendingList.length" :max="99" class="badge">
                  <el-button type="primary" @click="refreshData">
                    <el-icon><Refresh /></el-icon>
                    刷新
                  </el-button>
                </el-badge>
              </div>

              <el-table
                :data="pendingList"
                v-loading="loading"
                empty-text="暂无待审核记录"
                class="visitor-table"
              >
                <el-table-column prop="XM" label="姓名" width="100" />
                <el-table-column prop="LFRGSMC" label="公司名称" min-width="150" />
                <el-table-column prop="LXDH" label="联系电话" width="120" />
                <el-table-column prop="RS" label="来访人数" width="80" />
                <el-table-column prop="JCSY" label="进场事由" min-width="150" />
                <el-table-column prop="SGLX" label="施工类型" width="100" />
                <el-table-column prop="SQSJ" label="申请时间" width="120">
                  <template #default="{ row }">
                    {{ formatDate(row.SQSJ) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                  <template #default="{ row }">
                    <el-button-group>
                      <el-button
                        type="success"
                        size="small"
                        @click="showApproveDialog(row)"
                      >
                        通过
                      </el-button>
                      <el-button
                        type="danger"
                        size="small"
                        @click="showRejectDialog(row)"
                      >
                        驳回
                      </el-button>
                    </el-button-group>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>

            <!-- 已通过 -->
            <el-tab-pane label="已通过" name="approved">
              <div class="tab-header">
                <h3>已通过访客列表</h3>
                <el-button type="primary" @click="refreshData">
                  <el-icon><Refresh /></el-icon>
                  刷新
                </el-button>
              </div>

              <el-table
                :data="approvedList"
                v-loading="loading"
                empty-text="暂无已通过记录"
                class="visitor-table"
              >
                <el-table-column prop="XM" label="姓名" width="100" />
                <el-table-column prop="LFRGSMC" label="公司名称" min-width="150" />
                <el-table-column prop="LXDH" label="联系电话" width="120" />
                <el-table-column prop="RS" label="来访人数" width="80" />
                <el-table-column prop="JCSY" label="进场事由" min-width="150" />
                <el-table-column prop="SGLX" label="施工类型" width="100" />
                <el-table-column prop="YXQKSSJ" label="有效期开始" width="120">
                  <template #default="{ row }">
                    {{ formatDate(row.YXQKSSJ) }}
                  </template>
                </el-table-column>
                <el-table-column prop="YXQJSSJ" label="有效期结束" width="120">
                  <template #default="{ row }">
                    {{ formatDate(row.YXQJSSJ) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120" fixed="right">
                  <template #default="{ row }">
                    <el-button
                      type="warning"
                      size="small"
                      @click="showEndWorkDialog(row)"
                    >
                      结束施工
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>

            <!-- 已驳回 -->
            <el-tab-pane label="已驳回" name="rejected">
              <div class="tab-header">
                <h3>已驳回访客列表</h3>
                <el-button type="primary" @click="refreshData">
                  <el-icon><Refresh /></el-icon>
                  刷新
                </el-button>
              </div>

              <el-table
                :data="rejectedList"
                v-loading="loading"
                empty-text="暂无已驳回记录"
                class="visitor-table"
              >
                <el-table-column prop="XM" label="姓名" width="100" />
                <el-table-column prop="LFRGSMC" label="公司名称" min-width="150" />
                <el-table-column prop="LXDH" label="联系电话" width="120" />
                <el-table-column prop="RS" label="来访人数" width="80" />
                <el-table-column prop="JCSY" label="进场事由" min-width="150" />
                <el-table-column prop="BHYY" label="驳回原因" min-width="200" />
                <el-table-column prop="SQSJ" label="申请时间" width="120">
                  <template #default="{ row }">
                    {{ formatDate(row.SQSJ) }}
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-main>

      <!-- 底部 -->
      <el-footer class="app-footer">
        <div class="footer-content">
          <p>&copy; 2025 企业访客登记系统</p>
        </div>
      </el-footer>
    </el-container>

    <!-- 审核通过对话框 -->
    <el-dialog
      v-model="approveDialogVisible"
      title="审核通过"
      width="500px"
      :before-close="handleApproveClose"
    >
      <el-form
        ref="approveFormRef"
        :model="approveForm"
        :rules="approveRules"
        label-width="100px"
      >
        <el-form-item label="施工类型" prop="constructionType">
          <el-select
            v-model="approveForm.constructionType"
            placeholder="请选择施工类型"
            style="width: 100%"
          >
            <el-option label="电气施工" value="electrical" />
            <el-option label="管道施工" value="plumbing" />
            <el-option label="装修施工" value="renovation" />
            <el-option label="其他施工" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="施工开始时间" prop="startDate">
          <el-date-picker
            v-model="approveForm.startDate"
            type="date"
            placeholder="选择开始日期"
            style="width: 100%"
            :disabled-date="disabledStartDate"
          />
        </el-form-item>
        <el-form-item label="施工结束时间" prop="endDate">
          <el-date-picker
            v-model="approveForm.endDate"
            type="date"
            placeholder="选择结束日期"
            style="width: 100%"
            :disabled-date="disabledEndDate"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleApproveClose">取消</el-button>
        <el-button type="primary" @click="handleApprove" :loading="approveLoading">
          确定通过
        </el-button>
      </template>
    </el-dialog>

    <!-- 审核驳回对话框 -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="审核驳回"
      width="500px"
      :before-close="handleRejectClose"
    >
      <el-form
        ref="rejectFormRef"
        :model="rejectForm"
        :rules="rejectRules"
        label-width="100px"
      >
        <el-form-item label="驳回原因" prop="rejectReason">
          <el-input
            v-model="rejectForm.rejectReason"
            type="textarea"
            :rows="4"
            placeholder="请输入驳回原因"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleRejectClose">取消</el-button>
        <el-button type="primary" @click="handleReject" :loading="rejectLoading">
          确定驳回
        </el-button>
      </template>
    </el-dialog>

    <!-- 结束施工对话框 -->
    <el-dialog
      v-model="endWorkDialogVisible"
      title="结束施工"
      width="400px"
      :before-close="handleEndWorkClose"
    >
      <p>确定要结束该施工人员的施工吗？</p>
      <p class="warning-text">结束施工后，该访客的通行证将立即失效。</p>
      <template #footer>
        <el-button @click="handleEndWorkClose">取消</el-button>
        <el-button type="warning" @click="handleEndWork" :loading="endWorkLoading">
          确定结束
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import type { VisitorInfo } from '~/types/api'

const router = useRouter()

// 标签页状态
const activeTab = ref('pending')
const loading = ref(false)

// 模拟数据
const pendingList = ref<Partial<VisitorInfo>[]>([
  {
    id: '1',
    XM: '张三',
    LFRGSMC: '某某建筑公司',
    LXDH: '13800138000',
    RS: '3',
    JCSY: '电气设备安装',
    SGLX: '电气施工',
    SQSJ: '2025-10-14 10:00:00'
  },
  {
    id: '2',
    XM: '李四',
    LFRGSMC: '某某装修公司',
    LXDH: '13900139000',
    RS: '2',
    JCSY: '室内装修施工',
    SGLX: '装修施工',
    SQSJ: '2025-10-14 11:30:00'
  }
])

const approvedList = ref<Partial<VisitorInfo>[]>([
  {
    id: '3',
    XM: '王五',
    LFRGSMC: '某某工程公司',
    LXDH: '13700137000',
    RS: '5',
    JCSY: '管道维修',
    SGLX: '管道施工',
    YXQKSSJ: '2025-10-14',
    YXQJSSJ: '2025-10-20'
  }
])

const rejectedList = ref<Partial<VisitorInfo>[]>([
  {
    id: '4',
    XM: '赵六',
    LFRGSMC: '某某维修公司',
    LXDH: '13600136000',
    RS: '1',
    JCSY: '设备检修',
    BHYY: '施工时间填写错误',
    SQSJ: '2025-10-13 15:20:00'
  }
])

// 审核通过相关
const approveDialogVisible = ref(false)
const approveLoading = ref(false)
const approveFormRef = ref<FormInstance>()
const currentApproveItem = ref<Partial<VisitorInfo>>({})
const approveForm = ref({
  constructionType: '',
  startDate: '',
  endDate: ''
})

const approveRules: FormRules = {
  constructionType: [
    { required: true, message: '请选择施工类型', trigger: 'change' }
  ],
  startDate: [
    { required: true, message: '请选择施工开始时间', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择施工结束时间', trigger: 'change' }
  ]
}

// 审核驳回相关
const rejectDialogVisible = ref(false)
const rejectLoading = ref(false)
const rejectFormRef = ref<FormInstance>()
const currentRejectItem = ref<Partial<VisitorInfo>>({})
const rejectForm = ref({
  rejectReason: ''
})

const rejectRules: FormRules = {
  rejectReason: [
    { required: true, message: '请输入驳回原因', trigger: 'blur' },
    { min: 5, message: '驳回原因至少5个字符', trigger: 'blur' }
  ]
}

// 结束施工相关
const endWorkDialogVisible = ref(false)
const endWorkLoading = ref(false)
const currentEndWorkItem = ref<Partial<VisitorInfo>>({})

const formatDate = (dateString: string) => {
  if (!dateString) return '--'
  return dateString.split(' ')[0]
}

const disabledStartDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7
}

const disabledEndDate = (time: Date) => {
  if (!approveForm.value.startDate) return time.getTime() < Date.now() - 8.64e7
  const startDate = new Date(approveForm.value.startDate)
  const maxDate = new Date(startDate)
  maxDate.setDate(startDate.getDate() + 10)
  return time.getTime() < startDate.getTime() || time.getTime() > maxDate.getTime()
}

const showApproveDialog = (item: Partial<VisitorInfo>) => {
  currentApproveItem.value = item
  approveForm.value = {
    constructionType: '',
    startDate: '',
    endDate: ''
  }
  approveDialogVisible.value = true
}

const showRejectDialog = (item: Partial<VisitorInfo>) => {
  currentRejectItem.value = item
  rejectForm.value = {
    rejectReason: ''
  }
  rejectDialogVisible.value = true
}

const showEndWorkDialog = (item: Partial<VisitorInfo>) => {
  currentEndWorkItem.value = item
  endWorkDialogVisible.value = true
}

const handleApproveClose = () => {
  approveDialogVisible.value = false
  approveFormRef.value?.resetFields()
}

const handleRejectClose = () => {
  rejectDialogVisible.value = false
  rejectFormRef.value?.resetFields()
}

const handleEndWorkClose = () => {
  endWorkDialogVisible.value = false
}

const handleApprove = async () => {
  if (!approveFormRef.value) return

  try {
    await approveFormRef.value.validate()
    
    approveLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 从待审核列表移除
    const index = pendingList.value.findIndex((item: Partial<VisitorInfo>) => item.id === currentApproveItem.value.id)
    if (index !== -1) {
      const approvedItem = { ...pendingList.value[index], ...approveForm.value }
      pendingList.value.splice(index, 1)
      approvedList.value.push(approvedItem)
    }
    
    ElMessage.success('审核通过成功')
    approveDialogVisible.value = false
  } catch (error) {
    console.error('审核通过失败:', error)
  } finally {
    approveLoading.value = false
  }
}

const handleReject = async () => {
  if (!rejectFormRef.value) return

  try {
    await rejectFormRef.value.validate()
    
    rejectLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 从待审核列表移除
    const index = pendingList.value.findIndex((item: Partial<VisitorInfo>) => item.id === currentRejectItem.value.id)
    if (index !== -1) {
      const rejectedItem = { 
        ...pendingList.value[index], 
        BHYY: rejectForm.value.rejectReason 
      }
      pendingList.value.splice(index, 1)
      rejectedList.value.push(rejectedItem)
    }
    
    ElMessage.success('审核驳回成功')
    rejectDialogVisible.value = false
  } catch (error) {
    console.error('审核驳回失败:', error)
  } finally {
    rejectLoading.value = false
  }
}

const handleEndWork = async () => {
  endWorkLoading.value = true
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 从已通过列表移除
    const index = approvedList.value.findIndex((item: Partial<VisitorInfo>) => item.id === currentEndWorkItem.value.id)
    if (index !== -1) {
      approvedList.value.splice(index, 1)
    }
    
    ElMessage.success('施工结束成功')
    endWorkDialogVisible.value = false
  } catch (error) {
    console.error('结束施工失败:', error)
  } finally {
    endWorkLoading.value = false
  }
}

const refreshData = () => {
  loading.value = true
  // 模拟数据刷新
  setTimeout(() => {
    loading.value = false
    ElMessage.success('数据已刷新')
  }, 1000)
}

const goBack = () => {
  router.back()
}

onMounted(() => {
  // 初始化数据
  refreshData()
})
</script>

<style scoped>
.admin {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.layout-container {
  min-height: 100vh;
}

.app-header {
  background: transparent;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem 0;
}

.header-content {
  text-align: center;
}

.header-title {
  font-size: 2.5rem;
  margin-bottom: 0.5rem;
  font-weight: 300;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.header-subtitle {
  font-size: 1.1rem;
  opacity: 0.9;
  margin: 0;
}

.app-main {
  padding: 2rem 0;
  background: #f5f7fa;
}

.main-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.admin-tabs {
  margin-bottom: 2rem;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.tab-header h3 {
  margin: 0;
  color: #303133;
}

.badge {
  margin-right: 1rem;
}

.visitor-table {
  width: 100%;
}

.warning-text {
  color: #e6a23c;
  font-weight: 500;
}

.app-footer {
  background: #303133;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 1rem 0;
}

.footer-content {
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-container {
    padding: 0 15px;
  }
  
  .header-title {
    font-size: 2rem;
  }
  
  .header-subtitle {
    font-size: 1rem;
  }
  
  .tab-header {
    flex-direction: column;
    gap: 1rem;
    align-items: flex-start;
  }
  
  .visitor-table {
    font-size: 0.9rem;
  }
}
</style>
